package com.it.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.it.reggie.commen.R;
import com.it.reggie.entity.Category;
import com.it.reggie.entity.Setmeal;
import com.it.reggie.entity.SetmealDish;
import com.it.reggie.entity.SetmealDto;
import com.it.reggie.service.CategoryService;
import com.it.reggie.service.SetmealDishService;
import com.it.reggie.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.function.Function;

//套餐管理
@RestController
@RequestMapping("/setmeal")
@SuppressWarnings(value = "all")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private CategoryService categoryService;


    //添加操作
     @CacheEvict(value = "setmealCach",key = "#setmealDto.categoryId")
    @PostMapping
    public R add(@RequestBody SetmealDto setmealDto) {

        setmealService.save(setmealDto); //执行完添加套餐方法后，使用雪花算法自动生成id,封装到当前实体对象中

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();

        Long categoryId = setmealDto.getCategoryId();

        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(Category::getId, categoryId);

        Category one = categoryService.getOne(queryWrapper);

        String name = one.getName();

        setmealDto.setCategoryName(name);

        for (SetmealDish setmealDish : setmealDishes) {

            //当前套餐菜品，没有设置归属的套餐id (此字段非null，无默认值)

            setmealDish.setSetmealId(setmealDto.getId());

            setmealDishService.save(setmealDish);

        }

        return R.success("添加成功");

    }

    //查询套餐,和菜品的分页查询类似
    @GetMapping("/page")
    public R selectByPage(Integer page, Integer pageSize, String name) {

        List<SetmealDto> setmealDtos = new ArrayList<>();

        IPage<Setmeal> iPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
        qw.like(name != null, Setmeal::getName, name);
        setmealService.page(iPage, qw);
        List<Setmeal> records = iPage.getRecords();
        long total = iPage.getTotal();
        List<Category> categories = categoryService.list(null);
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();

        for (Setmeal record : records) {

            Long categoryId = record.getCategoryId();

            for (Category category : categories) {

                if (categoryId.equals(category.getId())) {

                    Long id = record.getId();
                    queryWrapper.eq(SetmealDish::getSetmealId, id);
                    List<SetmealDish> list = setmealDishService.list(queryWrapper);

                    SetmealDto setmealDto = new SetmealDto();
                    setmealDto.setSetmealDishes(list);

                    BeanUtils.copyProperties(record, setmealDto);
                    setmealDto.setCategoryName(category.getName());
                    setmealDtos.add(setmealDto);
                }
            }

        }

        Map map = new HashMap();

        map.put("total", total);
        map.put("records", setmealDtos);
        return R.success(map);

    }

    //删除套餐
    @CacheEvict(value = "setmealCach",allEntries = true)
    @DeleteMapping
    public R deleteByIds(@RequestParam List<Long> ids) {

        int count = 0;
        for (Long id : ids) {
            LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
            qw.eq(Setmeal::getId, id);
            //根据每一个id获取Setmeal对象
            Setmeal setmealServiceOne = setmealService.getOne(qw);

            //判断这个Setmeal是否为停售状态，是则可以删除
            if (setmealServiceOne.getStatus() == 0) {

                count = count + 1;
                setmealService.remove(qw);
                LambdaQueryWrapper<SetmealDish> qw2 = new LambdaQueryWrapper<>();
                qw2.eq(SetmealDish::getSetmealId, id);

                //删除Setmeal对应的SetmealDish
                setmealDishService.remove(qw2);

            }

        }
        if (count == 0) {

            return R.error("删除失败");
        } else {
            return R.success("删除成功");
        }

    }


    //修改状态
    @PostMapping("/status/{status}")
    public R updateStatus(@PathVariable Integer status, @RequestParam List<Long> ids) {

        Setmeal setmeal = new Setmeal();
        setmeal.setStatus(status);

        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();

        qw.in(Setmeal::getId, ids);

        setmealService.update(setmeal, qw);

        return R.success("修改成功");

    }

    //根据id查询信息
    @GetMapping("/{id}")
    @Cacheable(value = "setmeealCach" ,key = "id")
    public R selectById(@PathVariable Long id) {

        SetmealDto setmealDto = new SetmealDto();

        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();

        qw.eq(id != null, Setmeal::getId, id);

        //根据id查询获取setmeal对象
        Setmeal setmealServiceOne = setmealService.getOne(qw);

        //将数据复制到setmealDto里
        BeanUtils.copyProperties(setmealServiceOne, setmealDto);

        LambdaQueryWrapper<SetmealDish> qw2 = new LambdaQueryWrapper<>();

        qw2.eq(id != null, SetmealDish::getSetmealId, id);

        List<SetmealDish> list = setmealDishService.list(qw2);

        setmealDto.setSetmealDishes(list);

        return R.success(setmealDto);

    }

    //修改信息套餐信息
    @CacheEvict(value = "setmeealCach",key = "#setmealDto.categoryId")
    @PutMapping
    public R updateById(@RequestBody SetmealDto setmealDto) {

        setmealService.updateById(setmealDto);

        Long categoryId = setmealDto.getCategoryId();

        Long setmealId = setmealDto.getId();

        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();

        setmealDishLambdaQueryWrapper.eq(SetmealDish::getSetmealId, setmealId);

        // List<SetmealDish> list = setmealDishService.list(setmealDishLambdaQueryWrapper);

        setmealDishService.remove(setmealDishLambdaQueryWrapper);

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();

        for (SetmealDish setmealDish : setmealDishes) {

            setmealDish.setSetmealId(setmealId);

        }

        setmealDishService.saveBatch(setmealDishes);

        String categoryName = setmealDto.getCategoryName();

        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();

        qw.eq(Category::getId, categoryId);

        Category one = categoryService.getOne(qw);

        one.setName(categoryName);

        return R.success("修改成功");

    }


    //根据分类id查询该分类下的所有菜品集合

    @GetMapping("/list")
//    @Cacheable(value = "setmealCach" ,key = "#categoryId + '_' + #status")
    @Cacheable(value = "setmealCach", key = "#categoryId", unless = "#result==null")
    public R selectById(String categoryId, Integer status) {

        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();

        qw.eq(Setmeal::getCategoryId, categoryId);
        qw.eq(status != null, Setmeal::getStatus, status);

        List<Setmeal> list = setmealService.list(qw);

        return R.success(list);

    }
}
